package cn.six1943.deepchat.module.ai.agent;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.util.cache.CacheUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.six1943.deepchat.module.ai.dal.dataobject.model.ProviderInstDO;
import cn.six1943.deepchat.module.ai.service.model.ProviderInstService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.SneakyThrows;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.ExecutionException;

import static cn.iocoder.yudao.framework.common.util.cache.CacheUtils.buildCache;

public class ModelCache {

    private static final String AI_CACHE   ="ai";
    private static final String MODEL_CODE = "model:code:";
    private static final String MODEL_ID = "model:id:";
    private static final String MODEL_KEY_ID = "model_key:id:";
    private static final String API_CODE = "api:code:";

    private static ProviderInstService apiKeyService;


    private static final LoadingCache<Long, ModelWithKey> instCache = buildCache(Duration.ofHours(1L), // 过期时间 1 分钟
        new CacheLoader<Long, ModelWithKey>() {

            @Override
            public ModelWithKey load(Long id) {
                ProviderInstDO inst = getInstService().getProviderInst(id);
                if (ObjectUtil.isNotEmpty(inst)) {
                    ModelWithKey mk = BeanUtils.toBean(inst, ModelWithKey.class);
                    return mk;
                }
                return null;
            }

        });

    private static ProviderInstService getInstService() {
        if (apiKeyService == null) {
            apiKeyService = SpringUtil.getBean(ProviderInstService.class);
        }
        return apiKeyService;
    }

    @SneakyThrows
    public static ModelWithKey getModelWithKey(long id) {
        return instCache.get(id);
    }

}
